import requests
from requests import Session, Request
import urllib.parse

url = 'http://httpbin.org/get'


# 上传文件
def upload():
    file = open('e://download/1.txt', 'rb')
    # b_file = bytes(urllib.parse.urlencode(file), 'cp936')
    files = {'file': file}
    resp = requests.post(url, data=file)
    print(resp.text)


# 获取cookie
def getCookie():
    r = requests.get('http://www.baidu.com')
    print(r.cookies)
    for key, value in r.cookies.items():
        print('key:' + key, ';value:', value)


def cookieLogin():
    head = {'Cookie': '857fb436-621d-41ce-a343-1de6a3a43ad5; d_c0="AJCYZF5wSRGPTp1V9hES-l3atGqUgd9xTJU=|1589766179"; '
                      '_ga=GA1.2.1205372900.1589766182; '
                      'z_c0="2|1:0|10:1594950870|4:z_c0|92'
                      ':Mi4xRjFubkFRQUFBQUFBa0poa1huQkpFU1lBQUFCZ0FsVk4xbEwtWHdCalJlU0c2cVA4S1U5cWlKM3NJMlo1a2RqdGpB'
                      '|7735c4b8553cca1e77ed3cc102b9b52ed54725e39911a3be289cc81e4d4e442e"; tst=r; '
                      'q_c1=5a510895a1b1480ebb006d45443ae55f|1607415957000|1604393525000; '
                      '_xsrf=4fadbe11-8150-4b81-b3d4-a9265e231dcb; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1607513798,'
                      '1607573343,1607573742,1607577653; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1607577653; '
                      'KLBRSID=9d75f80756f65c61b0a50d80b4ca9b13|1607577654|1607572658; '
                      'SESSIONID=rln47fIcVO8o46odITD6V6Ep1ouYzQoHRfXRMNYRiXp; '
                      'JOID=VFAWB05poM-uB3E7HGsNVq5Q_boIFcemmzMZeXg84fzGMkRac1ocGPMKdDcavpRm8PtxRW2bgmDUPvf7388uL0U=; '
                      'osd=W1AWBUpmoM-sA347HGkJWa5Q_74HFceknzwZeXo47vzGMEBVc1oeHPwKdDUesZRm8v9-RW2Zhm_UPvX_0M8uLUE=',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
            'Host': 'www.zhihu.com'}

    resp = requests.get('https://www.zhihu.com', headers=head)
    print(resp.text)


# 会话维持
def setCookie():
    r = requests.Session()
    r.get('http://httpbin.org/cookies/set/number/123456789')
    r = r.get('http://httpbin.org/cookies')
    print(r.text)

    # SSL 证书验证
    requests.get('https://www.', verify=False)

    # 超时验证
    requests.get('www.zhihu.com', timeout=1)


# 身份验证
def auths():
    requests.get(url, auth=('username', 'password'))


# Prepared Request 将请求数据封装成包
def sendPackage():
    data = {'name': 'tqq'}
    url = 'http://httpbin.org/post'
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}
    s = Session()  # 会话维持
    req = Request('POST', url, data=data, headers=header)
    prepped = s.prepare_request(req)
    resp = s.send(prepped)
    print(resp.text)


sendPackage()
